//
//  AppController.m
//  iPing
//
//  Created by Aaron Hillegass on 11/5/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"


@implementation AppController


-(IBAction)newDocument:(id)sender
{	
	if (myWindowController == NULL)
		myWindowController = [[SGWindowController alloc] initWithWindowNibName:@"StoryGrabberWindow"];
	[myWindowController setManagedObjectContext:[self managedObjectContext]];
	[myWindowController showWindow:self];
}

// -------------------------------------------------------------------------------
//	applicationDidFinishLaunching:notification
// -------------------------------------------------------------------------------
- (void)applicationDidFinishLaunching:(NSNotification*)notification
{
	[self newDocument:self];
}

// -------------------------------------------------------------------------------
//	validateMenuItem:theMenuItem
// -------------------------------------------------------------------------------
-(BOOL)validateMenuItem:(NSMenuItem*)theMenuItem
{
    BOOL enable = [self respondsToSelector:[theMenuItem action]];
	
    // disable "New" if the window is already up
	if ([theMenuItem action] == @selector(newDocument:))
	{
		if ([[myWindowController window] isKeyWindow])
			enable = NO;
	}
	return enable;
}



- (id)init 
{
    if (![super init]) 
		return nil;
	
	//[self prepareViewControllers];
    return self;
}
- (void)dealloc
{
	[managedObjectContext release], managedObjectContext = nil;
    [persistentStoreCoordinator release], persistentStoreCoordinator = nil;
    [managedObjectModel release], managedObjectModel = nil;
	[super dealloc];
}
/*- (void)prepareViewControllers
{
	viewControllers = [[NSMutableArray alloc] init];
	
	NSViewController *vc;
	vc = [[StoryControllerView alloc] init];
	//[vc setManagedObjectContext:[self managedObjectContext]];
	[viewControllers addObject:vc];
	[vc release];
	
	vc = [[StoryLibraryView alloc] init];
	//[vc setManagedObjectContext:[self managedObjectContext]];
	[viewControllers addObject:vc];
	[vc release];
	
}*/
-  (void)windowControllerDidLoadNib:(NSWindowController *)windowController 
{
    [super windowControllerDidLoadNib:windowController];
	[self ShowWhatever:[viewControllers objectAtIndex:0]];
}
/*- (IBAction)showGrabber:(id)pId;
{
	NSViewController *vc = [[StoryControllerView alloc] init];
	[self ShowWhatever:vc];
}
- (IBAction)showLibrary:(id)pId;
{
	NSViewController *vc = [[StoryLibraryView alloc] init];
	[self ShowWhatever:vc];
}
- (void)ShowWhatever:(NSViewController *)vc
{
	NSLog(@"show whatever");
	NSWindow *w = [box window];
	BOOL ended = [w makeFirstResponder:w];
	if (!ended) {
		NSBeep();
		return;
	}
	NSView *v = [vc view];
	
	NSSize currentSize = [[box contentView] frame].size;
	
	NSSize newSize = [v frame].size;
	
	float deltaWidth = newSize.width - currentSize.width;
	float deltaHeight = newSize.height - currentSize.height;
	
	NSRect windowFrame = [w frame];
	windowFrame.size.height += deltaHeight;
	windowFrame.origin.y -= deltaHeight;
	windowFrame.size.width += deltaWidth;
	
	[box setContentView:nil];
	[w setFrame:windowFrame
		display:YES
		animate:YES];
	
	[box setContentView:v];
	
	// Put the view controller in the responder chain
	[v setNextResponder:vc];
	[vc setNextResponder:box];
}
- (IBAction)ShowStoryDownloader:(id)sender 
{ 
    // Is preferenceController nil? 
    if (!storyController) { 
		storyController = [[StoryController alloc] init]; 
    } 
    [storyController showWindow:self]; 
	[storyController loadWindow];
} */

#pragma mark Core Data Stuff
- (NSManagedObjectModel *)managedObjectModel {
	
    if (managedObjectModel != nil) {
        return managedObjectModel;
    }
	
    managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];    
    return managedObjectModel;
}
- (NSPersistentStoreCoordinator *) persistentStoreCoordinator {
	
    if (persistentStoreCoordinator != nil) {
        return persistentStoreCoordinator;
    }
	
    NSFileManager *fileManager;
    NSString *applicationSupportFolder = nil;
    NSURL *url;
    NSError *error;
    
    fileManager = [NSFileManager defaultManager];
    applicationSupportFolder = [self applicationSupportFolder];
    if ( ![fileManager fileExistsAtPath:applicationSupportFolder isDirectory:NULL] ) {
        [fileManager createDirectoryAtPath:applicationSupportFolder attributes:nil];
    }
    
	/* url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"Molecular.xml"]];
	 persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
	 if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]){
	 [[NSApplication sharedApplication] presentError:error];
	 }    
	 
	 return persistentStoreCoordinator;*/
	url = [NSURL fileURLWithPath: [applicationSupportFolder stringByAppendingPathComponent: @"Library.sgdb2"]];
	persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel: [self managedObjectModel]];
	if (![persistentStoreCoordinator addPersistentStoreWithType:NSXMLStoreType configuration:nil URL:url options:nil error:&error]){
		[[NSApplication sharedApplication] presentError:error];
	}    
	
	return persistentStoreCoordinator;
}
- (NSManagedObjectContext *) managedObjectContext {
	
    if (managedObjectContext != nil) {
        return managedObjectContext;
    }
	
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        managedObjectContext = [[NSManagedObjectContext alloc] init];
        [managedObjectContext setPersistentStoreCoordinator: coordinator];
    }
    
    return managedObjectContext;
}

- (NSUndoManager *)windowWillReturnUndoManager:(NSWindow *)window {
    return [[self managedObjectContext] undoManager];
}
- (NSString *)windowNibName 
{
    return @"MyDocument";
}
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
	
    NSError *error;
    int reply = NSTerminateNow;
    
    if (managedObjectContext != nil) {
        if ([managedObjectContext commitEditing]) {
            if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
				
                // This error handling simply presents error information in a panel with an 
                // "Ok" button, which does not include any attempt at error recovery (meaning, 
                // attempting to fix the error.)  As a result, this implementation will 
                // present the information to the user and then follow up with a panel asking 
                // if the user wishes to "Quit Anyway", without saving the changes.
				
                // Typically, this process should be altered to include application-specific 
                // recovery steps.  
				
                BOOL errorResult = [[NSApplication sharedApplication] presentError:error];
				
                if (errorResult == YES) {
                    reply = NSTerminateCancel;
                } 
				
                else {
					
                    int alertReturn = NSRunAlertPanel(nil, @"Could not save changes while quitting. Quit anyway?" , @"Quit anyway", @"Cancel", nil);
                    if (alertReturn == NSAlertAlternateReturn) {
                        reply = NSTerminateCancel;	
                    }
                }
            }
        } 
        
        else {
            reply = NSTerminateCancel;
        }
    }
    
    return reply;
}

#pragma mark interface/Core Data
- (NSString *)applicationSupportFolder {
	
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
	NSLog(@"savePath: %@",[basePath stringByAppendingPathComponent:@"Story Grabber"]);
    return [basePath stringByAppendingPathComponent:@"Story Grabber"];
}

- (IBAction) saveAction:(id)sender {
	
    NSError *error = nil;
    if (![[self managedObjectContext] save:&error]) {
        [[NSApplication sharedApplication] presentError:error];
    }
}
-(BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem {
    if ([anItem action] == @selector(undo:)) {
        return [[[self managedObjectContext] undoManager] canUndo];
    } 
    else if ([anItem action] == @selector(redo:)) {
        return [[[self managedObjectContext] undoManager] canRedo];
    }
    return YES;
}

-(IBAction)undo:sender {
    [[[self managedObjectContext] undoManager] undo];
}


-(IBAction)redo:sender {
    [[[self managedObjectContext] undoManager] redo];
}

@end
